import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView } from 'react-native';
import { Icon, List, ListItem, Button, SideMenu, SearchBar } from 'react-native-elements';
import Loader from './widgets/Loader';
import RefreshScrollView from './widgets/RefreshScrollView';
import StoreList from './components/StoreList';
import InfiniteList from './widgets/InfiniteList';
import { primaryColor, toast, loadMoreData, executor } from './utils';
import { StoragePageQuery } from './graphql';

const styles = StyleSheet.create({
  button: {
    paddingTop: 32
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  icon: {
    marginRight: 16
  },
  iconLeft: {
    marginLeft: 16
  },
  iconButton: {
    paddingHorizontal: 16
  }
});

class StoragePage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    const params = navigation.state.params;
    return {
      title: `Storage${(params&&params.selectStore)?`: ${params.selectStore.title}`:''}`,
      tabBarLabel: screenProps.chinese?`仓库`:`Storage`,
      tabBarIcon: ({tintColor}) => <Icon name='store' color={tintColor} size={24}/>,
      headerLeft: params&&params.selectStore&&(
        <TouchableOpacity onPress={()=>navigation.navigate('StoreEdit', params.selectStore)}>
          <Icon name='mode-edit' color={primaryColor} style={styles.iconLeft}/>
        </TouchableOpacity>
      ),
      headerRight: params&&params.selectStore&&(
        <TouchableOpacity onPress={()=>navigation.navigate('StoreCheckIn', {storeId: params.selectStore.id, title: params.selectStore.title})}>
          <Icon name='add' color={primaryColor} style={styles.icon}/>
        </TouchableOpacity>
      )
    };
  }
  state = {}
  onSideMenuChange = (isOpen) => this.setState({isOpen})
  onOpenMenu = () => this.setState({isOpen: true})
  onSelectStore = (store) => {
    this.setState({isOpen: false});
    if (store) {
      this.props.navigation.setParams({selectStore: store});
    } else {
      this.props.navigation.navigate('StoreEdit', {});
    }
  }
  onSelectChange = (selects) => this.setState({selects})
  onSearchChange =(search)=>{
    this.setState({search})
  }
  onSearch = () => {
    this.props.navigation.setParams({search:this.state.search});
  }
  onCheckIn = () => {
    const { selectStore } = this.props.navigation.state.params||{};
    if (!selectStore) return toast('Please select a store to check in to');

    this.props.navigation.navigate('StoreCheckIn', {storeId: selectStore.id, title: selectStore.title});
  }
  onMoveItem = () => {
    const { selects } = this.state;
    const { selectStore, search } = this.props.navigation.state.params||{};
    if (!selects||selects.length===0) return toast('Please select items to move');

    this.props.navigation.navigate('StoreMove', {itemIds: selects, storeId: selectStore&&selectStore.id, search,
      onSuccess: () => {
        this.setState({selects: []});
      }}); 
  }
  onCheckOut = () => {
    const { selects } = this.state;
    if (!selects||selects.length===0) return toast('Please select check out items');

    Alert.alert(
      `Are you sure you want to check out ${selects.length} order${selects.length>1?'s':''}?`,
      null,
      [
        {text: 'Cancel'},
        {text: 'Check Out', onPress: () => {
          executor(this.props.storeCheckOut, selects)
            .then(({res}) => {
              if (res) {
                toast('Check out succeed');
                this.setState({selects:[]});
              }
            });
          toast('Checking out...');
        }},
      ],
      { cancelable: true }
    );
  }
  renderItem = ({item:{content, location, type, order, id}, ...others}) => {
    const { selects } = this.state;
    const select = selects&&selects.indexOf(id)>=0;
    return <ListItem key={id} title={`#${content} [${location}]`} onPress={()=> {
        if (select) {
          const index = selects.indexOf(id);
          this.onSelectChange([...selects.slice(0,index), ...selects.slice(index+1)]);
        } else {
          this.onSelectChange([...selects||[], id]);
        }
      }}
      subtitle={order&&`${order.status.displayStatus} [${order.shipping.district}]`}
      rightIcon={{name:select?'check-box':'check-box-outline-blank',color:select?primaryColor:undefined}}/>;
  }
  render() {
    const { storeItems, loading, refetch, fetchMore } = this.props;

    return (
      <SideMenu isOpen={this.state.isOpen} onChange={this.onSideMenuChange}
        menu={<StoreList onSelect={this.onSelectStore}/>}>
        <View style={styles.container}>
          <RefreshScrollView refetch={refetch}>
            <View style={styles.row}>
              <TouchableOpacity onPress={this.onOpenMenu}>
                <Icon containerStyle={styles.iconButton} name='menu' color={primaryColor}/>
              </TouchableOpacity>
              <View style={styles.container}>
                <SearchBar inputStyle={{height:50}} placeholder='Search order' lightTheme keyboardType='numeric'
                  onChangeText={this.onSearchChange} value={this.state.search} showLoadingIcon={loading}/>
              </View>
              <TouchableOpacity onPress={this.onSearch}>
                <Icon containerStyle={styles.iconButton} name='search' color={primaryColor}/>
              </TouchableOpacity>
              <TouchableOpacity onPress={this.onMoveItem}>
                <Icon containerStyle={styles.iconButton} name='dns' color={primaryColor}/>
              </TouchableOpacity>
              <TouchableOpacity onPress={this.onCheckOut}>
                <Icon containerStyle={styles.iconButton} name='delete-forever' color={primaryColor}/>
              </TouchableOpacity>
            </View>
            <InfiniteList top hideEmpty datas={storeItems} loading={loading}
              refetch={refetch} fetchMore={fetchMore} extraData={{selects: this.props.selects}}
              renderItem={this.renderItem}/>
          </RefreshScrollView>
        </View>
      </SideMenu>
    );
  }
}

export default compose(
  graphql(StoragePageQuery, {
    options: ({navigation:{state:{params}}}) => {
      return {
        variables: {
          storeId: params&&params.selectStore&&params.selectStore.id,
          search: params&&params.search
        }
      };
    },
    props: ({ownProps:{navigation:{state:{params}}}, data:{storeItems, refetch, fetchMore, loading}}) => {
      return {
        storeItems,
        loading,
        refetch: () => {
          return refetch({variables:{
          storeId: params&&params.selectStore&&params.selectStore.id,
          search: params&&params.search
        }});
        },
        fetchMore: () => loadMoreData(fetchMore, storeItems, 'storeItems')
      };
    }
  }),
  graphql(gql`
    mutation storeCheckOut($itemIds:[String]!) {
      storeCheckOut(itemIds:$itemIds)
    }
  `, {
    name: 'storeCheckOut',
    props: ({ownProps:{navigation:{state:{params}}}, storeCheckOut}) => {
      return {
        storeCheckOut: (itemIds) => storeCheckOut({
          variables:{itemIds},
          refetchQueries: [{
            query: StoragePageQuery,
            variables: {
              storeId: params&&params.selectStore&&params.selectStore.id,
              search: params&&params.search
            },
          }],
        })
      };
    }
  })
)(StoragePage);

